package com.shop.loan.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.UserBankByMybatisMapper;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.UserBankByMybatis;
import com.shop.loan.model.vo.UpdateBankVo;
import org.springframework.stereotype.Component;
import xyz.erupt.annotation.fun.OperationHandler;

import javax.annotation.Resource;
import java.util.List;

@Component
public class UpdateOrderBankHandler implements OperationHandler<Object, UpdateBankVo> {

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    UserBankByMybatisMapper userBankByMybatisMapper;

    @Override
    public String exec(List<Object> data, UpdateBankVo updateBankVo, String[] param) {
        if (updateBankVo.getUserBank() == null) {
            return "msg.error('银行卡不能为空!')";
        }
        Object item = data.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
        Long id = jsonObject.getLongValue("id");
        LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(id);
        UserBankByMybatis userBankByMybatis = userBankByMybatisMapper.selectByPrimaryKey(updateBankVo.getUserBank().getId());
        if (userBankByMybatis.getIsDelete() == null || userBankByMybatis.getIsDelete()) {
            return "msg.error('银行卡状态异常!')";
        }

        if (userBankByMybatis.getUserId() != loanOrderByMybatis.getUserId().longValue()) {
            return "msg.error('银行卡归属异常!')";
        }

        LoanOrderByMybatis update = new LoanOrderByMybatis();
        update.setId(id);
        update.setBankId(updateBankVo.getUserBank().getId());
        loanOrderByMybatisMapper.updateByPrimaryKeySelective(update);
        return null;
    }


    @Override
    public UpdateBankVo eruptFormValue(List<Object> data, UpdateBankVo updateBankVo, String[] param) {
        Object item = data.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
        Long id = jsonObject.getLongValue("id");
        LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(id);

        updateBankVo.setOrderId(loanOrderByMybatis.getId());
        updateBankVo.setUserId(loanOrderByMybatis.getUserId());
        return OperationHandler.super.eruptFormValue(data, updateBankVo, param);
    }
}
